package cn.ecnu.gateway.filter;

import cn.ecnu.common.RedisConstant;
import cn.ecnu.vo.user.UserPermission;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        URI url = request.getURI();
        System.out.println(url + " FROM " + request.getRemoteAddress());
        if (StringUtils.contains(url.getPath(), "auth") || StringUtils.contains(url.getPath(), "sms"))  // 如果是认证请求, 直接放行
            return chain.filter(exchange);

        ServerHttpResponse response = exchange.getResponse();
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete(); // 如果没有token直接就返回没有授权
        }

        UserPermission o = (UserPermission) redisTemplate.opsForValue().get(RedisConstant.TOKEN_USER + token);

        if (o == null) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete(); // 如果redis没有对应的键直接就返回没有授权
        }

        request.mutate().header("userId", o.getUserId().toString())
                .header("permission", o.getRole())
                .build();
        // 将权限和用户id加入请求头
        return chain.filter(exchange);

    }


    @Override
    public int getOrder() {
        return 0;
    }
}
